import { JSONParse, JSONStringify } from './utils'

// 存储本地会话数据
export const setLocalStorage = <T>(key: string, v: T) => {
  try {
    window.localStorage.setItem(key, JSONStringify(v))
  } catch (error) {
    return false
  }
}

// 获取本地会话数据
export function getLocalStorage(k: string) {
  const item = window.localStorage.getItem(k)
  try {
    return item ? JSONParse(item) : item
  } catch (error) {
    return item
  }
}

// 清除临时会话数据
export const clearLocalStorage = (name: string) => {
  window.localStorage.removeItem(name)
}

// 存储临时会话数据
export const setSessionStorage = <T>(key: string, v: T) => {
  try {
    window.sessionStorage.setItem(key, JSONStringify(v))
  } catch (error) {
    return false
  }
}

// 获取临时会话数据
export const getSessionStorage = (k: string) => {
  const item = window.sessionStorage.getItem(k)
  try {
    return item ? JSONParse(item) : item
  } catch (error) {
    return item
  }
}

// 清除临时会话数据
export const clearSessionStorage = (name: string) => {
  window.sessionStorage.removeItem(name)
}

// 设置 cookie
export const setCookie = (name: string, cvalue: string, exdays: number) => {
  const d = new Date()
  d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000)
  const expires = 'expires=' + d.toUTCString()
  document.cookie = name + '=' + cvalue + ';' + expires
}

// 获取 cookie
export const getCookie = (cname: string) => {
  const name = cname + '='
  const ca = document.cookie.split(';')
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i]
    while (c.charAt(0) === ' ') c = c.substring(1)
    if (c.indexOf(name) != -1) return c.substring(name.length, c.length)
  }
  return ''
}

// 清除 cookie
export const clearCookit = (name: string) => {
  setCookie(name, '', -1)
}
